import React, { Component } from 'react'
import { Button, Drawer, Alert, Divider, Badge, Modal, Upload, Icon } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, compareNum, TableCustomize, openSuccessModal, openModalMessage } from '../../../components/TableCustomize';
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import { baseUrl, toLead } from '../../../config';
import * as APIService from '../../../axios/api_yq'
import { withPermission } from '../../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DeleteButton = withPermission(Button, 'line')
const QyButton = withPermission(Button, 'play-square')
const TyButton = withPermission(Button, 'poweroff')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')
export default class InspectionItem extends Component {
	state = {
		dataSource: [],
		inquire: [],
		paging: {},
		visible: false,
		formData: {},
		drawerVisible: false,
		drawerTitle: '',
		createTime: null,
		one: false,
		loading: false,
		some: null,
		selectedRows: [],
		advanced: false,
		values: {},
		selectedRowKeys: [],
		control: false,
		buttonList: [],
		buttonLoading: false
	};
	// 挂载前
	UNSAFE_componentWillMount() {
		this.fetch();
	}
	//初始化加载数据
	fetch = (page = 1, size = 100) => {
		const { values } = this.state
		const buttonList = JSON.parse(localStorage.getItem('buttonList'))
		console.log('这是按钮', buttonList);
		if (buttonList ? buttonList.length !== 0 : null) {
			this.setState({
				buttonList
			})
		}
		this.setState({
			loading: true,
			one: false,
			drawerVisible: false,
			formData: {},
			paging: { pageNum: page, pageSize: size }
		})
		let a = { pageNum: page, pageSize: size }
		setTimeout(() => {
			this.search({ ...values, ...a })
		}, 300);
	}
	// 查询接口
	search = (value, paging) => {
		APIService.queryByCondition(value, paging).then((item) => {
			// console.log('查询数据', item);
			if (item.data.code === 200) {
				this.setState({
					loading: false,
					dataSource: item.data.data.data,
					// 操作后清除选中
					selectedRowKeys: [],
					selectedRows: [],
					some: null,
					paging: {
						pageNum: item.data.data.pageNum,
						pageSize: item.data.data.pageSize,
						total: item.data.data.total,
					}
				})
			} else {
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 新增/修改接口
	newData = (data) => {
		const { formData, values, paging, one } = this.state
		APIService.alterCheckItem(data).then((item) => {
			if (item.data.code !== 200) {
				openModalMessage('error', item.data.msg)
				this.setState({
					buttonLoading: false
				})
				this.search({ ...values, ...paging })
				return
			}
			openSuccessModal(item.data.msg)
			this.handleCancel()
			this.search({ ...values, ...paging })
		})
	}
	// 删除接口
	deletes1 = (data) => {
		const { formData, values, paging, one } = this.state
		APIService.deleteCheckItem(data).then((item) => {
			if (item.data.code !== 200) {
				openModalMessage('error', item.data.msg)
				return
			}
			openSuccessModal(item.data.msg)
			this.search({ ...values, ...paging })
		})
	}
	// 当前行获得数据
	deleteRow1 = (b) => {
		console.log('编辑', b);
		this.setState({
			one: true,
			drawerVisible: true,
			formData: b,
			drawerTitle: '编辑'
		});
	}
	// 停用
	stop = (c) => {
		const { values, paging } = this.state
		let a = [c]
		a.forEach(item => {
			item.isDelete = 1
		})
		APIService.alterCheckItem({ 'list': a }).then((item) => {
			if (item.data.code === 200) {
				openSuccessModal(item.data.msg)
				this.search({ ...values, ...paging })
			} else {
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 启用
	startUsing = (c) => {
		const { values, paging } = this.state
		let a = [c]
		a.forEach(item => {
			item.isDelete = 0
		})
		APIService.alterCheckItem({ 'list': a }).then((item) => {
			if (item.data.code === 200) {
				this.search({ ...values, ...paging })
				openSuccessModal(item.data.msg)
			} else {
				openModalMessage('error', item.data.msg)
			}
		})
	}
	// 新增数据/修改
	onHandleOk = () => {
		const { formData, values, paging, one } = this.state
		// console.log(formData.id);
		this.formDrawer.validateFields((err, value) => {
			if (err) return;
			let amend = { ...value, id: formData.id }
			// console.log('数据', amend);
			// console.log('添加', value);
			this.setState({
				buttonLoading: true
			}, () => {
				this.newData(one === false ? value : amend)
			})

		})
	}
	// 取消
	handleCancel = e => {            //表单重置函数
		this.formAdd && this.formAdd.resetFields();
		this.formDrawer && this.formDrawer.resetFields();
		this.setState({
			visible: false,
			drawerVisible: false,
			one: false,
			formData: {},
			buttonLoading: false
		});
	};
	// 条件查询查询
	handleSearch = value => {
		console.log('查询数据', value);
		const { paging, values } = this.state
		let a = { pageNum: paging.pageNum, pageSize: paging.pageSize }
		this.setState({
			values: value
		})
		console.log({ ...values, ...a });
		this.search({ ...value, ...a })
	};
	//0新增
	create = () => {
		console.log('新增');
		this.setState({
			one: false,
			drawerVisible: true,
			drawerTitle: '新增',
			formData: {},
		});
	};
	// 全启
	allStart = () => {
		const { selectedRows, some, values, paging } = this.state
		let a = [...selectedRows]
		a.forEach(item => {
			item.isDelete = 0
		})
		console.log(some);
		if (some !== null && some > 0) {
			APIService.alterCheckItem({ 'list': a }).then((item) => {
				if (item.data.code === 200) {
					this.search({ ...values, ...paging })
					openSuccessModal(item.data.msg)
				} else {
					openModalMessage('error', item.data.msg)
				}
			})
		} else {
			openModalMessage('error', '未选中')
		}
	}
	// 全停
	allStop = () => {
		const { selectedRows, some, values, paging } = this.state
		let at = [...selectedRows]
		at.forEach(item => {
			item.isDelete = 1
		})
		if (some !== null && some > 0) {
			APIService.alterCheckItem({ 'list': at }).then((item) => {
				if (item.data.code === 200) {
					this.search({ ...values, ...paging })
					openSuccessModal(item.data.msg)
				} else {
					openModalMessage('error', item.data.msg)
				}
			})
		} else {
			openModalMessage('error', '未选中')
		}
	}
	// 导出模板
	derive = () => {
		APIService.exportExcelDemo().then(res => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('检验项目');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
		})
	}
	// 导出选中
	derive1 = () => {
		const { selectedRows } = this.state
		// 拿到的数据
		let selectedRowss = [...selectedRows]
		// console.log(selectedRowss);
		let a = {
			list: [
				...selectedRowss
			]
		}
		// console.log(a);
		if (this.state.some !== null && this.state.some > 0) {
			APIService.exportExcel(a).then(res => {
				// console.log('这是', res);
				//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
				let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
				// 创建A标签
				let link = document.createElement('a')
				link.style.display = 'none'
				link.href = url
				// 设置的下载文件文件名
				const fileName = decodeURI('检验项目');
				// 触发点击方法
				link.setAttribute('download', fileName)
				document.body.appendChild(link)
				link.click()
			})
		} else {
			openModalMessage('error', '请选中导出项')
		}
	}
	// table行修改数据
	loadData = (value, dataSource) => {
		const { formData, values, paging, one } = this.state
		// console.log('table行修改数据', value, dataSource)
		let amend = { ...value, checkStandardOption1: (value.checkStandardOption1 === true ? formData.checkStandardOption1 : ''), checkStandardOption2: (value.checkStandardOption2 === true ? formData.checkStandardOption2 : ''), checkStandardOption3: (value.checkStandardOption3 === true ? formData.checkStandardOption3 : ''), checkStandardOption4: (value.checkStandardOption4 == true ? formData.checkStandardOption4 : ''), checkStandardOption5: (value.checkStandardOption5 === true ? formData.checkStandardOption5 : '') }
		// console.log('数据', amend);
		// console.log('123', value);
		this.newData(amend)
	}
	// 重置
	cz = () => {
		this.setState({
			values: null
		}, () => { this.fetch() })
	}
	// 高级查询
	advancedss = () => {
		// console.log('高级查询');
		this.setState({ advanced: !this.state.advanced })
	}
	// 按钮点击事件
	// btnClick = (a) => {
	// 	if (a === 0) {
	// 		this.create()
	// 	}
	// 	if (a === 1) {
	// 		this.allStart()
	// 	}
	// 	if (a === 2) {
	// 		this.allStop()
	// 	}
	// 	if (a === 3) {
	// 		this.derive()
	// 	}
	// 	if (a === 4) {
	// 		this.derive1()
	// 	}
	// }
	// 选中删除
	selectDelete = () => {
		const { selectedRows, some } = this.state
		let a = [...selectedRows]
		let ids = []
		a.forEach(item => {
			ids.push(item.id)
		})
		let id = `idList=${ids}`
		if (some !== null && some > 0) {
			this.deletes1(id)
		} else {
			openModalMessage('error', '未选中')
		}
	}

	// 删除
	deletes = (item) => {
		const then = this
		let id = `idList=${[item.id]}`
		console.log('删除', id);
		Modal.confirm({
			title: '确认删除当项吗，这将影响其他数据模块?',
			onOk() {
				then.deletes1(id)
			},
			onCancel() {
			},
		})
	}

	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	render() {
		const then = this
		const { buttonLoading, buttonList, control, selectedRowKeys, advanced, some, one, paging, loading, dataSource, formData, drawerVisible, drawerTitle } = this.state;
		const rowSelection = {
			columnWidth: 60,
			type: 'checkbox',
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				let some = [...selectedRows].length
				this.setState({
					some: some,
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys
				}, () => {
					// console.log('选中个数', this.state.some, '选中详细数据', this.state.selectedRows);
				})
				if (some === 0 || some === null) {
					this.setState({
						control: false
					})
				} else {
					this.setState({
						control: true
					})
				}
			},
			// 固定在左侧
			// fixed: true
		}
		const columns = [
			{
				title: '序号',
				dataIndex: 'number',
				width: 50,
				align: 'center',
				fixed: 'left',
				render: (text, record, index) =>
					<div>
						{index + 1}
					</div>
			},
			{
				title: '检验编码',
				dataIndex: 'checkItemCode',
				width: 100,
			},

			{
				title: '检验名称',
				width: 100,
				dataIndex: 'checkItemName',
			},
			{
				title: '所属表单',
				width: 100,
				dataIndex: 'formProperties',
			},
			{
				title: '第一类机型',
				width: 100,
				dataIndex: 'checkTypeFirst',
			},
			{
				title: '第二类分类',
				width: 100,
				dataIndex: 'checkTypeSecond',
			},
			{
				title: '排序层级',
				width: 100,
				sorter: (a, b) => compareNum(a.sort, b.sort),
				dataIndex: 'sort',
				editable: true,
			},
			{
				title: '检验属性',
				width: 100,
				dataIndex: 'checkItemProperty',
				render: (text, record) =>
					<div>
						{
							record.checkItemProperty === 1 ? <span>范围</span> : record.checkItemProperty === 2 ? <span>文本</span> : record.checkItemProperty === 3 ? <span>唯一值</span> : record.checkItemProperty === 4 ? <span>复选</span> : null
						}
					</div>
			},
			{
				title: '检验范围最小值',
				width: 120,
				dataIndex: 'checkStandardMin',
			},
			{
				title: '检验范围最大值',
				width: 120,
				dataIndex: 'checkStandardMax',
			},
			{
				title: '是否包含最小值',
				width: 120,
				dataIndex: 'containMin',
				render: (text, record) =>
					<div>
						{
							record.containMin === 1 ? '包含' : '不包含'
						}
					</div>
			},
			{
				title: '是否包含最大值',
				width: 120,
				dataIndex: 'containMax',
				render: (text, record) =>
					<div>
						{
							record.containMax === 1 ? '包含' : '不包含'
						}
					</div>
			},
			{
				title: '单位',
				width: 80,
				dataIndex: 'unit',
			},
			{
				title: '检验文本',
				width: 100,
				dataIndex: 'checkStandardText',
			},
			{
				title: '检验选项1',
				width: 100,
				dataIndex: 'checkStandardOption1',
			},
			{
				title: '检验选项2',
				width: 100,
				dataIndex: 'checkStandardOption2',
			},
			{
				title: '检验选项3',
				width: 100,
				dataIndex: 'checkStandardOption3',
			},
			{
				title: '检验选项4',
				width: 100,
				dataIndex: 'checkStandardOption4',
			},
			{
				title: '检验选项5',
				width: 100,
				dataIndex: 'checkStandardOption5',
			},

			{
				title: '备注文本',
				width: 100,
				dataIndex: 'remark',
			},
			{
				title: '状态',
				dataIndex: 'isDelete',
				width: 100,
				fixed: 'right',
				render: (text, record) =>
					record.isDelete === 1 ? <Badge status="error" text={'停用'} /> : <Badge status='success' text={'启用'} />
			},
			{
				title: '操作',
				dataIndex: 'opts',
				width: 160,
				fixed: 'right',
				render:
					(text, record) =>
						<div>
							<a onClick={this.deleteRow1.bind(this, record)}>{'编辑'}</a>
							<Divider type="vertical" />
							<a onClick={this.deletes.bind(this, record)}>{'删除'}</a>
							<Divider type="vertical" />
							{
								record.isDelete === 1 ? <a onClick={this.startUsing.bind(null, record)} >{'启用'}</a> : <a onClick={this.stop.bind(null, record)} >{'停用'}</a>
							}
						</div>
			},
			{ dataIndex: '' }
		]
		// 导入
		const propss = {
			name: 'file',
			action: `${baseUrl}${toLead}/machinemanager/importExcel`,
			accept: '.xls,.xlsx',
			method: 'post',
			showUploadList: true,
			headers: {
				userId: localStorage.getItem('userId'),
				Token: localStorage.getItem('token'),
			},
			onChange(info) {
				console.log('这是', info);
				if (info.file.status !== 'uploading') {
					console.log('这是什么', info.file, info.fileList);
				}
				if (info.file.status === 'done') {
					openSuccessModal('导入成功')
					then.fetch()
				} else if (info.file.status === 'error') {
					openModalMessage('error', '错误')
				}
			},
		}
		return (
			<div>
				<BasicLayoutSearch>
					<SearchForm onSearch={this.handleSearch}
						onClick={this.cz}
						onClick1={this.advancedss}
						advanced={advanced}
					/>
				</BasicLayoutSearch>
				{
					control === true ? <Alert message={<div>已选择 <span style={{ color: '#5abcff' }}>{some}</span> 项 </div>} type="info" showIcon style={{ width: '99%', margin: 'auto' }} /> : null
				}
				<BasicLayout
					name="检验项目"
					icon="table"
					buttons={[
						<CreateButton key={1} onClick={this.create} icon='plus' />,
						<DeleteButton key={2} onClick={this.selectDelete} icon='delete' />,
						<QyButton key={5} onClick={this.allStart} icon='play-square' />,
						<TyButton key={7} onClick={this.allStop} icon='poweroff' />,
						<DownLoadButton key={3} onClick={this.derive} icon='download' text="导出模板" />,
						<DownLoadButton key={4} onClick={this.derive1} icon='download' text="导出选中" />,
						<Upload {...propss} key={6}>
							<UploadButton icon="upload" />
						</Upload>,

						// <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
						// <Button key={22} onClick={this.selectDelete} type="primary" icon='line'>删除</Button>,
						// <Button key={2} onClick={this.allStart} type="primary" icon='play-square'>启用</Button>,
						// <Button key={3} onClick={this.allStop} type="primary" icon='poweroff'>停用</Button>,
						// <Button key={4} onClick={this.derive} type="primary" icon='download'>导出模板</Button>,
						// <Button key={5} onClick={this.derive1} type="primary" icon='download'>导出选中</Button>,
						// <Upload {...propss} key={6}>
						// 	<Button type="primary">
						// 		<Icon type="upload" /> 导入
						// 	</Button>
						// </Upload>,
					]}
				// buttons={[
				// 	buttonList.length !== 0 ? buttonList.map((value, index) => {
				// 		return value.buttonName === '导入' ? <Upload {...propss} key={`${5}_upload`}>
				// 			<Button type="primary">
				// 				<Icon type="upload" /> 导入
				// 			</Button>
				// 		</Upload> : <Button key={value.id} onClick={this.btnClick.bind(this, index)} type={value.description} icon={value.buttonCode}>{value.buttonName}</Button>
				// 	}) : null,
				// ]}
				>
					<TableCustomize
						rowSelection={rowSelection}
						columns={columns}
						rowKey={(record) => record.id}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						allowEditable={this.loadData}
						scroll={{ x: true, y: 600 }}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
						}}
					/>
					<BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
				</BasicLayout>
				<Drawer
					width={500}
					visible={drawerVisible}
					title={drawerTitle}
					onClose={this.handleCancel}
					destroyOnClose
				>
					<AddForm
						formData={formData}
						one={one}
						onOk={this.onHandleOk}
						ref={node => (this.formDrawer = node)}
						onClose={this.handleCancel}
					/>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
						<Button type="primary" onClick={this.onHandleOk} loading={buttonLoading}>
							{'确认'}
						</Button>
					</div>
				</Drawer>
			</div>
		);
	}
}